package com.infocollect.project.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.infocollect.common.utils.ip.AddressUtils;
import com.infocollect.project.api.entity.TappFromEntity;
import com.infocollect.project.api.helper.JSONUtil;
import com.infocollect.project.api.mapper.TappFromMapper;
import com.infocollect.project.api.req.ConfigQueryJsonReq;
import com.infocollect.project.api.req.CustQueryFormReq;
import com.infocollect.project.api.service.ITappApiConfigBackService;
import com.infocollect.project.api.service.ITappApiConfigService;
import com.infocollect.project.api.service.ITappApiConfigService;
import com.infocollect.project.api.service.ITappFromService;
import com.infocollect.project.api.vo.AuditOperatorVo;
import com.infocollect.project.form.vo.HeadEntityVO;
import com.infocollect.project.form.vo.R;
import com.infocollect.project.grant.domain.QuestionAuditProcess;
import com.infocollect.project.grant.service.IQuestionAuditProcessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.infocollect.project.api.vo.ApiConfigVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * (TappFrom)表服务实现类
 *
 * @author makejava
 * @since 2019-12-25 10:32:29
 */
@Service("tappFromService")
public class TappFromServiceImpl extends ServiceImpl<TappFromMapper, TappFromEntity> implements ITappFromService {
    private static final Logger logger = LoggerFactory.getLogger(TappFromServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    ITappApiConfigService tappApiConfigService;
    @Autowired
    IQuestionAuditProcessService auditProcessService;

    /**
     * 通过ID查询单条数据
     *
     * @param fid 主键
     * @return 实例对象
     */
    @Override
    public TappFromEntity queryById(Long fid) {
        return this.baseMapper.selectById(fid);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<TappFromEntity> queryAllByLimit(int offset, int limit) {
        return this.baseMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param tappFrom 实例对象
     * @return 实例对象
     */
    @Override
    public TappFromEntity insert(TappFromEntity tappFrom) {
        this.baseMapper.insert(tappFrom);
        return tappFrom;
    }

    /**
     * 修改数据
     *
     * @param tappFrom 实例对象
     * @return 实例对象
     */
    @Override
    public TappFromEntity update(TappFromEntity tappFrom) {
        this.baseMapper.updateById(tappFrom);
        return this.queryById(tappFrom.getFid());
    }

    /**
     * 通过主键删除数据
     *
     * @param fid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long fid) {
        return this.baseMapper.deleteById(fid) > 0;
    }

    /**
     * 查询多条数据
     * @menu 根据实体对象是否有值 进行查询
     * @return 对象列表
     */
    @Override
    public List<TappFromEntity> queryAll(TappFromEntity entity){
        LambdaQueryWrapper<TappFromEntity> lambdaQueryWrapper = new LambdaQueryWrapper();
        return this.baseMapper.selectList(lambdaQueryWrapper) ;
    }
    /**
     *
     * @menu 根据表名查询表单信息
     * @return 对象列表
     */
    @Override
    public TappFromEntity querybyTableName(String strTableName){
        QueryWrapper<TappFromEntity> lambdaQueryWrapper = new QueryWrapper();
        lambdaQueryWrapper.eq("from_table_name",strTableName);
        List<TappFromEntity> formlist= this.baseMapper.selectList(lambdaQueryWrapper) ;
        if(formlist!=null&&formlist.size()>0){
            return formlist.get(0);
        }
        return null;
    }

    @Override
    public List<JSONObject> getImportData(List<Map<String, Object>> dataList, Long formId, boolean updateSupport) {
        TappFromEntity fromEntity =  this.baseMapper.selectById(formId);
        String tableCode = fromEntity.getFromTableName();
        Map<String,String > headMap = getImportHeadMap(tableCode);
        List<JSONObject> importDataList = new ArrayList<>();
        dataList.stream().forEach(dataMap ->{
            JSONObject dataObject = new JSONObject();
            Long $tableNewId = IdWorker.getId();
            String zjhm = "";
            for (Map.Entry<String, Object> entry : dataMap.entrySet()){
                if(entry.getKey()==null || StringUtils.isBlank(entry.getKey()) || StringUtils.isBlank(headMap.get((String) entry.getKey()))){
                    continue;
                }
                System.out.println(entry.getKey());
                dataObject.put(headMap.get((String) entry.getKey()),entry.getValue());
                if(("证件号码".equals((String) entry.getKey()) || "身份证号".equals((String) entry.getKey())) && updateSupport){
                    //去判断一下证件号码有没有重复的，写死了用证件号码判断
                    String sql = "select * from "+ tableCode +" where "+headMap.get((String) entry.getKey())+ "='"+entry.getValue()+"'";
                    List<Map<String,Object>> datalist = jdbcTemplate.queryForList(sql);
                    if(datalist.size()>0){
                        Map<String,Object> data = datalist.get(0);
                        $tableNewId = Long.parseLong((String)data.get("fid"));
                    }
                }
            }
            dataObject.put("$tableNewId",$tableNewId);
            dataObject.put("isimport","是");
            importDataList.add(dataObject);
            //.SaveDataInfo

        });
        return importDataList;
    }

    @Override
    public R<String> auditOperator(AuditOperatorVo param) {
//        TappFromEntity fromEntity =  this.baseMapper.selectById(param.getFormId());
//        String tableCode = fromEntity.getFromTableName();
        String sql = "update "+param.getTableName()+" set auditdate=SYSDATE(),auditflag='"+param.getAuditflag()+"',auditremark='"+param.getAuditremark()+"'";
        sql += " where fid='"+param.getTableNewId()+"'";
        logger.info("更新审核信息SQL"+sql);
        jdbcTemplate.execute(sql);
        QuestionAuditProcess auditProcess = new QuestionAuditProcess();
        auditProcess.setAuditby(param.getAuditby());
        auditProcess.setAuditbyname(param.getAuditbyname());
        auditProcess.setAuditflag(param.getAuditflag());
        auditProcess.setAuditremark(param.getAuditremark());
        auditProcess.setCreateby(param.getAuditby());
        auditProcess.setCreatebyname(param.getAuditbyname());
        auditProcess.setCreatedate(new Date());
        auditProcess.setTablename(param.getTableName());
        auditProcess.setFid(Long.valueOf(param.getTableNewId()));
        auditProcessService.insertQuestionAuditProcess(auditProcess);
        return R.newOk();
    }
    //随机提取10条记录，更新到当前用户下面
    @Override
    public R<String> extractAuditData(String userId, String username,String fromTableName) {
        if(StringUtils.isBlank(userId) || StringUtils.isBlank(username)){
            return R.newError("提取人不能为空");
        }
        String sql = "select count(1) from "+fromTableName+" where  auditflag = '审核中' and auditby = '"+userId+"'";
        final Integer rowCount= jdbcTemplate.queryForObject(sql,Integer.class);
        if(rowCount>0){
            return R.newError("请先全部审核完成");
        }
        sql = "update "+fromTableName+" set auditby='"+userId+"', auditbyname='"+username+"',auditdate = SYSDATE(),auditflag='审核中' WHERE auditflag = '未审核' order by flastupdatedate limit 10";
        int num = jdbcTemplate.update(sql);
        if(num==0){
            return R.newError("没有可以提取的记录。");
        }
        return R.newOk();
    }
    //随机提取1条记录，更新到当前用户下面，并返回数据id，如果当用户下面还有记录，直接返回
    @Override
    public R<String> lockAuditData(String userId, String username,String fromTableName) {
        if(StringUtils.isBlank(userId) || StringUtils.isBlank(username)){
            return R.newError("提取人不能为空");
        }
        String sql = "select fid from "+fromTableName+" where  auditflag = '审核中' and auditby = '"+userId+"'";
        final List<String> fids= jdbcTemplate.queryForList(sql,String.class);
        if(fids.size()>0){
            return R.newOk(fids.get(0));
        }
        sql = "update "+fromTableName+" set auditby='"+userId+"', auditbyname='"+username+"',auditdate = SYSDATE(),auditflag='审核中' WHERE auditflag = '未审核' order by flastupdatedate limit 1";
        int num = jdbcTemplate.update(sql);
        if(num==0){
            return R.newError("没有可以提取的记录。");
        }
        sql = "select fid from "+fromTableName+" where  auditflag = '审核中' and auditby = '"+userId+"'";
        final List<String> newfids= jdbcTemplate.queryForList(sql,String.class);
        if(newfids.size()>0){
            return R.newOk(newfids.get(0));
        }else
        {
            return R.newError("没有可以提取的记录。");
        }
    }
    @Override
    public R<String> lockRecord(String userId, String username,JSONObject param)
    {
        if(StringUtils.isBlank(userId) || StringUtils.isBlank(username)){
            return R.newError("提取人不能为空");
        }

        String apiCode = param.getString("apiCode");
        ApiConfigVO apiconfig = tappApiConfigService.getApiConfigByCallMethodCode(apiCode);
        String idFieldName = "";
        List<HeadEntityVO> headEntityList = new ArrayList<>();
        if (org.apache.commons.lang.StringUtils.isNotBlank(apiconfig.getHeadList())) {
            headEntityList = JSONUtil.jsonToObjList(HeadEntityVO.class, apiconfig.getHeadList());
            for (int i = 0; i < headEntityList.size(); i++) {
                HeadEntityVO headEntity = headEntityList.get(i);

                if(headEntity.getHeadname().equals("证件号码")||headEntity.getHeadname().equals("身份证号")) {
                    idFieldName = headEntity.getBindname();
                    break;
                }
            }
        }
        if("".equals(idFieldName))
        {
            return R.newError("没有证件号码字段，提取失败");
        }
        String sql = "update "+param.getString("fromTableName")+" set auditby='"+userId+"', auditbyname='"+username+"',auditdate = SYSDATE(),auditflag='审核中' WHERE "+
                idFieldName+"='"+param.getString("auditIdCode")+"' order by flastupdatedate limit 1";
        int num = jdbcTemplate.update(sql);
        if(num==0){
            return R.newError("记录不存在，请确认");
        }else {
            return R.newOk("记录提取成功");
        }

    }
/**
 * @author dongpj
 * @date 2022/8/27 10:47
 * @param userId, userName
 * @return com.infocollect.project.form.vo.R<java.lang.String>
 * @describe 释放指定人员已提取的数据
 */
    @Override
    public R<String> unExtractAuditData(String userId, String userName,String fromTableName) {
        String sql = "update "+fromTableName+" set auditby='',auditbyname='',auditdate = NULL,auditflag='未审核' WHERE auditflag = '审核中' and auditby = '"+userId+"'";
        jdbcTemplate.execute(sql);
        return  R.newOk();
    }
//释放指定记录
    @Override
    public R<String> unExtractFidAuditData(String fromTableName, String fid) {
        String sql = "update "+fromTableName+" set auditby='',auditbyname='',auditdate = NULL,auditflag='未审核' WHERE auditflag = '审核中' and fid = "+fid;
        jdbcTemplate.execute(sql);
        return  R.newOk();
    }
    //获取待审核的下一条记录
    @Override
    public R<String> getNextAuditData(String userId, String fromTableName) {
        String sql = "select fid from "+fromTableName+" where  auditflag = '审核中' and auditby = '"+userId+"' limit 1";
        List<String> auditList = jdbcTemplate.queryForList(sql,String.class);
        if(auditList.size()>0){
            String fid = auditList.get(0);
            return R.newOk(fid);
        }
        return R.newError("当前记录审核成功,下面已没有待审核的记录,请重新获取！");
    }

    public Map<String,String> getImportHeadMap(String tableCode){
        String callMothedName = tableCode+".querylist";
        ApiConfigVO apiConfigVO = tappApiConfigService.getApiConfigByCallMethodCode(callMothedName);
        String headList = apiConfigVO.getHeadList();
        JSONArray headJsonArray = JSONArray.fromObject(headList);
        Map<String,String > headMap = new HashMap<>(headJsonArray.size());
        headJsonArray.stream().forEach(headObject ->{
            JSONObject jsonObject = (JSONObject)headObject;
            headMap.put(jsonObject.getString("headname"),jsonObject.getString("bindname"));
        });
        return headMap;
    }
    /**
     * 返回表单设计字段
     * @param fid
     * @return
     */
    @Override
    public String GetFromDesignJson(Long fid){
        return this.baseMapper.GetFromDesignJson(fid) ;
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param tappFrom 实例对象
     * @return 对象列表
     */
    @Override
    public  List<TappFromEntity> querypageList(TappFromEntity tappFrom){
        return this.baseMapper.querypageList(tappFrom) ;
    }



    /**
     * 保存设置查询条件
     * @return
     */
    @Override
    public boolean saveConfigQueryJson(ConfigQueryJsonReq param){
        TappFromEntity fromEntity= baseMapper.selectById(param.fid);
        if(fromEntity==null)
            return false;
        fromEntity.setQueryJson(param.getQueryJson());
        baseMapper.updateById(fromEntity);
        return true;
    }

    /**
     * 获取查询条件的配置
     * @param fid
     * @return
     */
    @Override
    public String getConfigQueryJson(Long fid){
        TappFromEntity fromEntity= baseMapper.selectById(fid);
        if(fromEntity==null)
            return null;
        return fromEntity.getQueryJson();
    }

    /**
     * 根据openId查项目数据id
     * @param custQueryFormReq
     * @return
     */
    @Override
    public Long getFromFidByOpenId(CustQueryFormReq custQueryFormReq)
    {
        Long fid = baseMapper.getFromFidByOpenId(custQueryFormReq);

        return fid;
    }
    /**
     * 根据证件号码查项目数据id
     * @param custQueryFormReq
     * @return
     */
    @Override
    public Long getFromFidByIDNum(CustQueryFormReq custQueryFormReq)
    {
        Long fid = baseMapper.getFromFidByIDNum(custQueryFormReq);

        return fid;
    }

    /**
     * 查询所有在报名的项目
     *
     * @return 对象列表
     */
    @Override
    public List<TappFromEntity> queryAllByIsUse()
    {
        return baseMapper.queryAllByIsUse();
    }

    /**
     * 修改数据
     *
     * @param tappFrom 实例对象
     * @return 实例对象
     */
    @Override
//    @Transactional()
    public void updateTestA() {
        TappFromEntity tappFrom = new TappFromEntity();
        tappFrom.setFid(30L);
        tappFrom.setFromname("工工");
        baseMapper.updateById(tappFrom);

        tappApiConfigService.updateTestA();
    }

    @Override
//    @Transactional()
    public void updateTestB(){
        TappFromEntity tappFrom = new TappFromEntity();
        tappFrom.setFid(34L);
        tappFrom.setFromname("bbbbbbb");
        baseMapper.updateById(tappFrom);
         tappFrom = new TappFromEntity();
        tappFrom.setFid(33L);
        tappFrom.setFromname("sssssssssssssssssssssssssssssssssssssssssssssrtestb");
        baseMapper.updateById(tappFrom);
    }

}
